<script setup lang="ts">
import { createUserInstance } from '@/api/code';
import { getImageList, getInstanceList } from '@/api/docker';
import { Image, Instance, UserContainer } from '@/api/docker/type';
import { useUserStore } from '@/store/user';
import { showNotify } from 'vant';
import { CascaderOption } from 'vant';
import { onMounted, Ref, ref } from 'vue';

const show = defineModel() as Ref<boolean>;
const instanceList = ref<Instance[]>([]);
const cascaderValue = ref<(string | number)[]>([]);
const options = ref<CascaderOption[]>([]);
const container = ref<UserContainer>({} as UserContainer);
const isCreating = ref(false);

const onSubmit = async () => {
    if (!container.value.instanceId || !container.value.imageId) {
        showNotify({
            type: 'warning',
            message: '请选择实例和镜像',
            position: 'top'
        });
        return;
    }
    
    try {
        isCreating.value = true;
        const userStore = useUserStore();
        const userId = userStore.getId;
        
        await createUserInstance(container.value.instanceId, container.value.imageId, userId);
        
        showNotify({
            type: 'success',
            message: '创建实例成功',
            position: 'top'
        });
        
        show.value = false;
    } catch (error) {
        console.error('创建实例失败:', error);
        showNotify({
            type: 'danger',
            message: '创建实例失败',
            position: 'top'
        });
    } finally {
        isCreating.value = false;
    }
}

const onFinish = ({selectedOptions}: { value: string | number, selectedOptions: CascaderOption[], tabIndex: number }) => {
    if (selectedOptions.length >= 2) {
        container.value.instanceId = selectedOptions[0].value as string;
        container.value.imageId = selectedOptions[1].value as string;
    }
}

onMounted(async () => {
    try {
        // 获取实例列表
        const res = await getInstanceList();
        instanceList.value = res.data as Instance[];
        
        // 并发获取每个实例的镜像列表
        await Promise.all(instanceList.value.map(async instance => {
            try {
                const res = await getImageList(instance.id);
                const imageList = res.data as Image[];
                
                if (imageList.length > 0) {
                    const option = {
                        text: `${instance.name} (${instance.id.substring(0, 8)})`,
                        value: instance.id,
                        children: [] as CascaderOption[]
                    };
                    
                    imageList.forEach(image => {
                        if (image.repoTags && image.repoTags.length > 0) {
                            option.children.push({
                                text: image.repoTags[0],
                                value: image.id
                            });
                        }
                    });
                    
                    options.value.push(option);
                }
            } catch (error) {
                console.error(`获取实例 ${instance.id} 的镜像列表失败:`, error);
            }
        }));
    } catch (error) {
        console.error('获取实例列表失败:', error);
        showNotify({
            type: 'danger',
            message: '获取实例列表失败',
            position: 'top'
        });
    }
})
</script>

<template>
    <van-dialog 
        v-model:show="show" 
        title="创建容器实例"
        show-cancel-button 
        :confirm-button-text="isCreating ? '创建中...' : '确认创建'"
        :confirm-loading="isCreating"
        @confirm="onSubmit"
        @closed="onFinish"
        width="90%"
        max-width="500px"
    >
        <div class="create-container-form">
            <div class="form-description">
                请选择要使用的实例和镜像，创建您的容器环境
            </div>
            
            <van-cascader
                v-model="cascaderValue"
                title="选择实例和镜像"
                :options="options"
                placeholder="点击选择实例和镜像"
                @finish="onFinish"
            />
            
            <div v-if="container.instanceId && container.imageId" class="selection-preview">
                <div class="preview-item">
                    <span class="label">已选实例:</span>
                    <span class="value">{{ container.instanceId.substring(0, 8) }}...</span>
                </div>
                <div class="preview-item">
                    <span class="label">已选镜像:</span>
                    <span class="value">{{ container.imageId.substring(0, 8) }}...</span>
                </div>
            </div>
        </div>
    </van-dialog>
</template>

<style lang="scss" scoped>
.create-container-form {
    padding: 16px;
    
    .form-description {
        margin-bottom: 16px;
        color: #646566;
        font-size: 14px;
    }
    
    .selection-preview {
        margin-top: 16px;
        padding: 12px;
        background-color: #f7f8fa;
        border-radius: 8px;
        font-size: 14px;
        
        .preview-item {
            margin-bottom: 8px;
            
            &:last-child {
                margin-bottom: 0;
            }
            
            .label {
                color: #969799;
                margin-right: 8px;
            }
            
            .value {
                font-weight: 500;
                color: #323233;
            }
        }
    }
}
</style>